package com.jjshome.Consumer;

import api.leyoujia.platform.hr.IMdsDeptService;
import api.leyoujia.platform.hr.output.DeptModel;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.leyoujia.platform.common.model.DubboResultModel;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ConsumerClient extends AbstractJavaSamplerClient {

    private ClassPathXmlApplicationContext CONTEXT;
    private SampleResult sampleResult;

    @Autowired
    private IMdsDeptService iMdsDeptService;

    // @Reference(lazy = false,timeout = 5000)
    // private IMdsDeptService iMdsDeptService;

    /**
     * 指定传入的参数，用于在Jmeter中添加参数
     */
    @Override
    public Arguments getDefaultParameters() {
        Arguments params = new Arguments();
        params.addArgument("deptNumber", "0002880");
        return params;
    }

    /**
     * 初始化加载配置文件
     * @param context 加载消费者中的ID来实现调
     */

    @Override
    public void setupTest(JavaSamplerContext context) {
        CONTEXT = new ClassPathXmlApplicationContext("spring-dubbo-customer.xml");
        getLogger().info("加载xml文件中对应的BeamName的值");
        iMdsDeptService = (IMdsDeptService) CONTEXT.getBean("iMdsDeptService");
    }

    /**
     * @param javaSamplerContext 传入一个取样器来实现对时间的操作和结果的操作
     * @return 返回产生的结果
     */
    @Override
    public SampleResult runTest(JavaSamplerContext javaSamplerContext) {
        sampleResult = new SampleResult();
        String param = javaSamplerContext.getParameter("deptNumber");
        // param = "0002880";
        getLogger().info(param+ "--------------");
        CONTEXT.start();
        //开始计时
        sampleResult.sampleStart();
        try {
            DubboResultModel<DeptModel> temp = iMdsDeptService.getDeptByNumber(param);
            DeptModel deptModel = temp.getData();
            String result = JSON.toJSONString(deptModel);
            getLogger().info(result);
            if (result.contains(param)){
                sampleResult.setResponseData(result,"UTF-8");
                sampleResult.setSuccessful(true);
            }
        }catch (Exception e){
            sampleResult.setResponseData(e.getMessage(), "UTF-8");
            sampleResult.setSuccessful(false);
        }
        return sampleResult;
    }

    /**
     * @param context 结束并销毁
     */
    @Override
    public void teardownTest(JavaSamplerContext context) {
        // 结束技计时
        sampleResult.sampleEnd();
        CONTEXT.close();
    }
}
